A structure in C is a user-defined data type that allows you to group different variables of different data types under a single name. It enables you to create more complex data structures to represent real-world entities, combining related data into a single unit.
To define a structure in C, you use the struct keyword followedby the structure name and a list of member variables within curly braces.
struct struct_name {
data_type member1;
data_type member2;
// ...
};
#include <stdio.h>
// Define a structure representing a point in 2D space
struct Point {
int x;
int y;
};
int main() {
// Declare and initialize a structure variable
struct Point p1 = {3, 7};
// Accessing structure members using the dot operator
printf("Point coordinates: x = %d, y = %d\n", p1.x, p1.y);
// Modifying structure members
p1.x = 10; // Change the value of x to 10
p1.y = -5; // Change the value of y to -5
// Accessing and printing the modified structure members
printf("Modified Point coordinates: x = %d, y = %d\n", p1.x, p1.y);
return 0;
}
Point coordinates: x = 3, y = 7
Modified Point coordinates: x = 10, y = -5
What is a structure in C?
What does a structure group together?
What is a member of a structure called?
What is used to access structure members?
Can structures contain members of different types?